package com.archgeek.rpc.thrfit;

import com.archgeek.rpc.thrfit.gen.StudentService.Client;
import org.apache.commons.pool2.impl.GenericObjectPool;

/**
 * @author pizhihui
 * @date 2022-04-07 10:53
 */
public class SocketPool {

    private GenericObjectPool<Client> clientPool;


    public SocketPool(String host, int port) {
        clientPool = new GenericObjectPool<>(new ClientFactory(host, port));

        // 配置
        clientPool.setMaxTotal(1);
//        clientPool.setMaxIdle(10);
//        clientPool.setMinIdle(0);

        clientPool.setTestWhileIdle(true);
        clientPool.setMinEvictableIdleTimeMillis(60000);
        clientPool.setTimeBetweenEvictionRunsMillis(30000);
        clientPool.setNumTestsPerEvictionRun(-1);
    }


    public Client getClicent() throws Exception {
        if (clientPool == null || clientPool.isClosed()) {
            return null;
        }
        return clientPool.borrowObject();
    }


    public void releaseClient(Client client) {
        clientPool.returnObject(client);
    }


    public int getNumActiveClient() {
        return clientPool.getNumActive();
//        if (null == clientPool) {
//            return 0;
//        } else {
//            return clientPool.getNumActive();
//        }
    }


    public int getNumIdleClient() {
        if (null == clientPool) {
            return 0;
        } else {
            return clientPool.getNumIdle();
        }
    }


    public int getMaxPoolSize() {
        if (null == clientPool) {
            return 0;
        } else {
            return clientPool.getMaxTotal();
        }
    }

    public void setMaxPoolSize(int size) {
        clientPool.setMaxTotal(size + 2);
    }

    public int getMinIdle() {
        return clientPool.getMinIdle();
    }



}
